package com.beidouapp.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Created by mhuang on 2016/9/16.
 */
public class PasswordAuthenticatorUtil {

    public static final String ALGORITHM = "MD5";

    public static final int SALT = 12;

    public static final int ALEN = 16;

    /**
     * @param password 需要产行密文的明文
     * @return String MD5加密后的密文
     * @throws Exception 出错后抛出异常
     */
    public static String encryptPassword(String password) {
        SecureRandom random = new SecureRandom();
        byte salt[] = new byte[SALT];
        random.nextBytes(salt);
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(salt);
            md.update(password.getBytes("UTF8"));
            byte digest[] = md.digest();
            BASE64Encoder encoder = new BASE64Encoder();
            String saltText = encoder.encode(salt);
            String encryptPwd = encoder.encode(digest);
            return saltText + encryptPwd;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 匹配输入的口令
     *
     * @return boolean如果能匹配返回true，否则返回false
     */
    public static boolean comparePassword(String inputPassword, String originalPassword) {
        String encryptPwd = originalPassword.substring(PasswordAuthenticatorUtil.ALEN, originalPassword.length());
        String salt = originalPassword.substring(0, PasswordAuthenticatorUtil.ALEN);

        try {
            BASE64Decoder dncoder = new BASE64Decoder();
            byte saltData[] = dncoder.decodeBuffer(salt);
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            md.update(saltData);
            md.update(inputPassword.getBytes("UTF8"));
            byte digest[] = md.digest();
            BASE64Encoder encoder = new BASE64Encoder();
            String encryptInputPwd = encoder.encode(digest);
            return encryptPwd.equals(encryptInputPwd);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
